package com.example.demo.netty.client.nio;

import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;
import java.util.Scanner;


/**
 * @author Kevin
 * @date 2020/4/18 23:47
 */
public class ModBusClient {
    private Selector selector;
    private SocketChannel channel;

    public void init(String ip, int port) throws IOException {
        // 创建Socketchannel并设置为非阻塞模式
        channel = SocketChannel.open();
        channel.configureBlocking(false);
        // 创建Selector并绑定到（Channel）Socket上
        this.selector = SelectorProvider.provider().openSelector();
        channel.connect(new InetSocketAddress(ip, port));
        // 将Channel和Selector绑定
        channel.register(selector, SelectionKey.OP_CONNECT);
    }

    public void working() throws IOException {
        //客户端一连接就可以写数据向服务器了
        new sendMessThread().start();

        while (true) {
            if (!selector.isOpen()) {
                break;
            }
            //阻塞，直至得到已准备好的Connect事件,或者Read事件
            selector.select();
            Iterator<SelectionKey> ite = this.selector.selectedKeys().iterator();
            while (ite.hasNext()) {
                SelectionKey key = ite.next();
                ite.remove();
                // 连接事件发生
                if (key.isConnectable()) {
                    connect(key);
                } else if (key.isReadable()) {
                    read(key);
                }
            }
        }
    }

    private void connect(SelectionKey key) throws IOException {
        SocketChannel channel = (SocketChannel)key.channel();
        // 如果正在连接，则完成连接
        if (channel.isConnectionPending()) {
            channel.finishConnect();
        }
        channel.configureBlocking(false);
        //channel.write(ByteBuffer.wrap(new String("hello server\r\n").getBytes()));
        channel.register(this.selector, SelectionKey.OP_READ);
    }

    private void read(SelectionKey key) throws IOException {
        SocketChannel channel = (SocketChannel) key.channel();
        // 创建读取的缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(100);
        channel.read(buffer);
        byte[] data = buffer.array();
        //16进制数组转字符串
        String msg = DatatypeConverter.printHexBinary(data).trim();
        System.out.println("客户端收到消息：" + msg);
        channel.close();
        key.selector().close();
    }

    class sendMessThread extends Thread {

        @Override
        public void run() {
            super.run();

            //构造输入
            byte[] request = new byte[]{0x30, 0x03, 0x00, 0x08, 0x00, 0x01, 0x01, (byte)0xE9};
            try {
                channel.write(ByteBuffer.wrap(request));
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) throws IOException {
        NIOClient client = new NIOClient();
        client.init("localhost", 8000);
        client.working();
    }
}
